package com.jn.okhttppicasso_demo01;



import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.jn.okhttppicasso_demo01.R;

import com.jn.okhttppicasso_demo01.adapter.ImageAdapter;
import com.jn.okhttppicasso_demo01.entity.ImageData;
import com.jn.okhttppicasso_demo01.service.BingResponse;
import com.squareup.picasso.Picasso;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ImageAdapter adapter;
    private List<ImageData> dataList = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ma);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        fetchData();
    }

    private void fetchData() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.oioweb.cn/api/bing")
                .build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to fetch data", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    runOnUiThread(() -> {
                        parseData(responseData);
                    });
                }
            }
        });
    }

    private void parseData(String jsonData) {
        Gson gson = new Gson();
        BingResponse response = gson.fromJson(jsonData, BingResponse.class);
        if (response.getCode() == 200) {
            dataList.clear(); // Clear previous data
            dataList.addAll(response.getResult());
            adapter = new ImageAdapter(MainActivity.this, dataList);
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged(); // Notify adapter about data change
        } else {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to fetch data: " + response.getMsg(), Toast.LENGTH_SHORT).show());
        }
    }
}